

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layuiAdmin 后台管理员</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="/layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="/layuiadmin/style/admin.css" media="all">
</head>
<body>

  <div class="layui-fluid">   
    <div class="layui-card">
      <div class="layui-form layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-block">
              <input type="text" name="supplierName" placeholder="请输入名称" autocomplete="off" class="layui-input" id="supplierName">
            </div>
          </div>
          <div class="layui-inline">
            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="search">
              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
            </button>
          </div>
        </div>
      </div>
      
      <div class="layui-card-body">
        <div style="padding-bottom: 10px;">
          <button class="layui-btn layuiadmin-btn-admin" data-type="add">添加</button>
          <button class="layui-btn layuiadmin-btn-admin" data-type="import" id="importData" style="margin-right: 10px;">导入</button>
          <button class="layui-btn layuiadmin-btn-admin" data-type="export">导出</button>
          <button class="layui-btn layuiadmin-btn-admin" data-type="batchdel">批量删除</button>

        </div>
        <!--表格-->
        <table id="supplier-list" lay-filter="supplier-list"></table>

        <script type="text/html" id="table-useradmin-admin">
          <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
          {{#  if(d.role == '超级管理员'){ }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-delete"></i>删除</a>
          {{#  } else { }}
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
          {{#  } }}
        </script>
      </div>


    </div>
  </div>
  <script src="/jquery-3.2.1.min.js"></script>
 <script src="/layuiadmin/layui/layui.js"></script>
  <script src="/layuiadmin/layui/excel.js"></script>

  <script>
  layui.config({
    base: '/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index','excel','table','upload'], function(){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table;

    //方法级渲染
    var initTable = table.render({
      elem: '#supplier-list'
      ,url: '/supplier/findData.do'
      ,cols: [
        [
          {type: 'checkbox', fixed: 'left'}
          // , {field: 'id', width: 100, title: 'ID', width: 80, sort: true}
          , {field: 'name', title: '供应商名称', width: 100}
          , {field: 'phone', title: '供应商电话', width: 120}
          , {field: 'email', title: '供应商邮箱', width: 100}
          , {field: 'address', title: '供应商地址',}
          , {field: 'type', title: '供应商类型', width: 120}
          , {title: '操作', width: 210, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin'}
        ]
      ]
      ,id: 'testReload'
      ,page: true
      ,height:'full-110'
    });

    //监听搜索
    form.on('submit(search)', function(data){
      var field = data.field;
      //执行重载
      //执行重载(这里reload后面的ID是render后面的ID)
      table.reload('testReload', {
        where: {
          name: $("#supplierName").val()
        },
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    });

      var upload = layui.upload;
    upload.render({ //允许上传的文件后缀
      elem: '#importData'
      ,url: '/supplier/upload.do/' //改成您自己的上传接口
      ,accept: 'file' //普通文件
      ,exts: 'xls|xlsx|txt|csv' //只允许上传压缩文件
      ,done: function(result){
        if (result.ret){
          //执行重载
          layer.msg('导入成功！', {
            offset: 'auto'
            , icon: 1
          }, function () {
            table.reload('testReload');
          });
        }else {
          layer.msg("导入失败!", {icon: 5});
        }
      }
    });

    //事件
    var active = {
      batchdel: function(){
        var checkStatus = table.checkStatus('testReload');
        var ids = [];
        var checkData = checkStatus.data;
        if(checkData.length == 0){
          return layer.msg('请选择要删除的数据');
        }
          layer.confirm('确定删除吗？', function(index) {
            $(checkData).each(function(index,val){
              var id = val.id;
              ids.push(id);
            });
            //执行 Ajax 后重载
            $.ajax({
              url: '/supplier/batchdel.do',
              type: 'POST',
              data: JSON.stringify(ids),
              contentType: "application/json;charset=UTF-8",
              success: function (result) {
                if (result){
                  //执行重载
                  layer.msg('删除成功', {
                    offset: 'auto'
                    , icon: 1
                  }, function () {
                    table.reload('testReload');
                  });
                }else {
                  layer.msg("删除失败!", {icon: 5});
                }
              },
              error: function (errorMsg) {
                layer.msg("删除失败!" + errorMsg, {icon: 5});
                table.reload('testReload');
              },
            });
            layer.closeAll(); //关闭弹层
            // table.reload('supplier-list');
          });
      }
      ,add: function(){
        layer.open({
          //跳转页面是个隐藏div的时候用type=1，若是个地址的时候type=2
          type: 1
          ,title: '添加供应商'
          ,content: $("#addForm")
          ,area : 'auto'
        });
        // 监听提交按钮
        form.on('submit(addBtn)',function (data) {
          var field = data.field;
          // 向数据库添加数据
          $.ajax({
            url: '/supplier/add.do',
            type: 'POST',
            data: JSON.stringify(field),
            contentType: "application/json;charset=UTF-8",
            success: function (result) {
              if (result.ret){
                //执行重载
                layer.msg('添加成功', {
                  offset: 'auto'
                  , icon: 1
                }, function () {
                  table.reload('testReload');
              });
              }
            },
            error: function (errorMsg) {
              layer.msg("数据异常!" + errorMsg, {icon: 5});
              location.reload();
            },
          });
          layer.closeAll(); //关闭弹层
        })
      },

      export: function(){ //导出
        /*var excel = layui.excel;
        //先从后台获取要导出的数据
        $.ajax({
          url: '/supplier/export.do',
          type: 'POST',
          dataType: 'json'
          , success: function (res) {
            var data = res.data;
            data = '[{"address":"成都","email":"admin@sina.com","id":1,"name":"供应商1","phone":"11111111111","type":"一级供应商"},{"address":"北京","email":"xiaowang@sina.com","id":2,"name":"供应商2","phone":"18978878780","type":"二级供应商"}]';
            data = excel.filterExportData(data, {
              id: 'id'
              , name: 'name'
              , phone: 'phone'
              , address: 'address'
              , email: 'email'
              , type: 'type'
            })

            data.unshift({
              id:'id',
              name: "供应商名称",
              phone: '供应商电话',
              address: '地址',
              email: '邮箱',
              type: '类型'
            })
            excel.exportExcel({
              sheet1: data
            }, 'test.xlsx', 'xlsx')
          }
          , error: function () {
            layer.alert('获取数据失败，请检查是否部署在本地服务器环境下')
          }
        })*/
        //传递一个对象到后台
        var gridParams = {
          ps : {
            name: $('#supplierName').val(),
          },
          pageSize: ''
        };
        var headInfo = "供应商名称,"+"供应商电话,"+"地址,"+"邮箱,"+"供应商类型,"
        exportData("/supplier/exportData.do",JSON.stringify(gridParams),headInfo)
      }
    }
    // 监听行工具事件使用该事件的时候要将按钮那里添加lay-event="edit",lay-event="del"
    table.on('tool(supplier-list)', function (obj) {
      var data = obj.data;
      if (obj.event === 'del') {
        layer.confirm('真的删除吗！', function (index) {
          //异步像服务器发送删除请求
          $.ajax({
            url: '/supplier/del.do',
            type: 'POST',
            data: {'id': data.id},
            success: function (result) {
              if (result.ret == true) {
                layer.msg("删除成功!", {icon: 6});
                obj.del();
                layer.close(index);
              } else {
                layer.msg("删除失败!", {icon: 5});
                layer.close(index);
              }
            },
            error: function (errorMsg) {
              layer.msg("数据异常!" + errorMsg, {icon: 5});
              layer.close(index);
              location.reload();
            },
          });
        });
        //更新用户
      } else if (obj.event == 'edit') {
        layer.open({
          type: 1,
          title: "更新供应商",
          area: 'auto',
          content: $("#updateSupplier"),
          success: function () {
            //回显数据
            $("#updateSupplier").find($("input[name='name']")).val(data.name);
            $("#updateSupplier").find($("input[name='email']")).val(data.email);
            $("#updateSupplier").find($("input[name='phone']")).val(data.phone);
            $("#updateSupplier").find($("input[name='address']")).val(data.address);
            $("#updateSupplier").find($("input[name='type']")).val(data.type);
          },
        });
        updateData(data);
      }
    });


    $('.layui-btn.layuiadmin-btn-admin').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
    function updateData(obj){
      form.on('submit(updateBtn)',function(data){
        var supplier = {
          id:obj.id,
          name:data.field.name,
          phone:data.field.phone,
          email:data.field.email,
          address:data.field.address,
          type:data.field.type,
        }
        $.ajax({
          url: '/supplier/update.do',
          type: 'POST',
          data: JSON.stringify(supplier),
          contentType: "application/json;charset=UTF-8",
          success: function (result) {
            if (result.ret){
              //执行重载
              layer.msg("修改成功",{icon: 6},{time:3000} );
              layer.closeAll();//关闭所有的弹出层
              table.reload('testReload', {
                page: {
                  curr: 1 //重新从第 1 页开始
                }
              }, 'data');
            }
          },
          error: function (errorMsg) {
            layer.msg("数据异常!" + errorMsg, {icon: 5});
            layer.closeAll();//关闭所有的弹出层
            location.reload();
          },
        });
      });
    }
    //该方法是用来实现导出功能的
    function exportData(action,gridParams,headInfo){
      action = action;
      form = $("<form></form>")
      form.attr('action',action)
      form.attr('method','post')
      input1 = $("<input type='hidden' name='data'/>")
      input1.attr('value',gridParams)
      input2 = $("<input type='hidden' name='headInfo'/>")
      input2.attr('value',headInfo)
      form.append(input1)
      form.append(input2)
      form.appendTo("body")
      form.css('display','none')
      form.submit()
    }
    /**
     * 上传excel的处理函数，传入文件对象数组
     * @param  {[type]} files [description]
     * @return {[type]}       [description]
     */
    function uploadExcel(files) {
      layui.use(['excel', 'layer'], function () {
        var excel = layui.excel
        var layer = layui.layer
        try {
          excel.importExcel(files, {
            // 读取数据的同时梳理数据
            fields: {
              'name': 'A'
              , 'phone': 'B'
              , 'address': 'C'
              , 'email': 'D'
              , 'type': 'E'
            }
          }, function (data) {
            // 还可以再进行数据梳理
            /*						data = excel.filterImportData(data, {
                    'id': 'A'
                    ,'username': 'B'
                    ,'experience': 'C'
                    ,'sex': 'D'
                    ,'score': 'E'
                    ,'city': 'F'
                    ,'classify': 'G'
                    ,'wealth': 'H'
                    ,'sign': 'I'
                  });
            */
            // 如果不需要展示直接上传，可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
            alert(JSON.stringify(data))
            $.ajax({
              url: '/supplier/import.do',
              type: 'POST',
              data: JSON.stringify(data),
              contentType: "application/json;charset=UTF-8",
              success: function (result) {
                if (result.ret){
                  //执行重载
                  layer.msg("上传成功",{icon: 6},{time:3000} );
                }
              },
              error: function (errorMsg) {
                layer.msg("数据异常!" + errorMsg, {icon: 5});
              },
            });
          })
        } catch (e) {
          layer.alert(e.message)
        }
      })
    }
    //判断浏览器大小方法
    function screen() {
      //获取当前窗口的宽度
      var width = $(window).width();
      if (width > 1200) {
        return 3;   //大屏幕
      } else if (width > 992) {
        return 2;   //中屏幕
      } else if (width > 768) {
        return 1;   //小屏幕
      } else {
        return 0;   //超小屏幕
      }
    }
  });
  </script>

</body>
<!-- 导入页面 -->
<!--<div id="dialog-import1" align="center" class="hide container">-->
<!--  <form enctype="multipart/form-data" class ="form-horizontal">-->
<!--    <div class="form-group">-->
<!--      <input id="file-1" name="uploadFile" type="file" multiple class="file-loading" data-overwrite-initial="false" data-min-file-count="1">-->
<!--    </div>-->
<!--  </form>-->
<!--</div>-->
<!--<div class="layui-row" id="dialog-import" style="display: none">-->
<!--  <div class="layui-form" lay-filter="layuiadmin-form-admin"  style="padding: 20px 30px 0 0;">-->
<!--    <div class="layui-form-item">-->
<!--      <div class="layui-input-inline">-->
<!--        <input id="file-1" name="uploadFile" type="file" multiple class="file-loading" data-overwrite-initial="false" data-min-file-count="1">-->
<!--      </div>-->
<!--    </div>-->
<!--  </div>-->
<!--</div>-->
<!--  end -->
<!--新增隐藏模块-->
<div class="layui-row" id="addForm" style="display: none">
  <div class="layui-form" lay-filter="layuiadmin-form-admin" id="layuiadmin-form-admin" style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
      <label class="layui-form-label">供应商名称</label>
      <div class="layui-input-inline">
        <input type="text" name="name" lay-verify="required" placeholder="请输入供应商名称" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">电话</label>
      <div class="layui-input-inline">
        <input type="text" name="phone" lay-verify="required" placeholder="请输入号码" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">邮箱</label>
      <div class="layui-input-inline">
        <input type="text" name="email" lay-verify="email" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">地址</label>
      <div class="layui-input-inline">
        <input type="text" name="address" lay-verify="required" placeholder="请输入地址" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">供应商类型</label>
      <div class="layui-input-inline">
        <input type="text" name="type" lay-verify="required" placeholder="请输入供应商类型" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="addBtn">立即提交</button>
      </div>
    </div>
  </div>
</div>
<!--修改隐藏模块-->
<div class="layui-row" id="updateSupplier" style="display: none">
  <div class="layui-form" lay-filter="layuiadmin-form-admin" style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
      <label class="layui-form-label">供应商名称</label>
      <div class="layui-input-inline">
        <input type="text" name="name" lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">手机</label>
      <div class="layui-input-inline">
        <input type="text" name="phone" lay-verify="phone" placeholder="请输入号码" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">邮箱</label>
      <div class="layui-input-inline">
        <input type="text" name="email" lay-verify="email" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">地址</label>
      <div class="layui-input-inline">
        <input type="text" name="address" lay-verify="required" placeholder="请输入地址" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">供应商类型</label>
      <div class="layui-input-inline">
        <input type="text" name="type" lay-verify="required" placeholder="请输入供应商类型" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="updateBtn">确认修改</button>
      </div>
    </div>
  </div>
</div>

</html>

